package it.rossignoli.enrico.app.Tesi;

import it.rossignoli.enrico.app.Tesi.RFIDActivity.ResponseReceiverRFID;

import java.util.ArrayList;
import java.util.HashMap;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class MappingActivity extends Activity{
	
	private ListView listView;
	private TextView textDialog;
	private ProgressDialog connecting;
	
	private static final String LOG_TAG="SimpleAdapterMyActivity";
	private static final String GESTURE="gesture";
	private static final String DEVICE_EVENT="deviceEvent";
	public static final String NULL_ELEMENT="nothing";
	
	private ArrayList<String> gestureList=new ArrayList<String>();
	private ArrayList<String> eventNotSelectedListView=new ArrayList<String>();
	private ArrayList<HashMap<String,String>> completeMapping=new ArrayList<HashMap<String,String>>();
	
	
	
	private ArrayList<String> masterGestureList=new ArrayList<String>();
	private ArrayList<String> masterEventNotSelectedListView=new ArrayList<String>();
	
	
	private ResponseReceiverMapping receiver;
	private IntentFilter filter;
	private Intent superintent;
	
	private static final int CHOOSE_MAPPING=1;
	
	private static final int DIALOG_CONFERM_MAPPING = 2;
	private static final int DIALOG_INFO_ID=3;
	
	private static final int ITEM_MENU_LEAVE=9;
	private static final int ITEM_MENU_INFO=8;
	
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.sel);
        
        superintent=getIntent();
        gestureList=superintent.getStringArrayListExtra("SMARTOBJECT_GESTURELIST");
        eventNotSelectedListView=superintent.getStringArrayListExtra("DEVICE_EVENTLIST");
        
        String v[]=new String[2];
        for(int i=0;i<gestureList.size();i++)
        {
        	masterGestureList.add(gestureList.get(i));
        	if(SibIntentService.DEBUG) Log.i(LOG_TAG,gestureList.get(i));
        	v=gestureList.get(i).split("#");
        	gestureList.set(i, v[1]);
        }

        String t[]=new String[2];
        for(int i=0;i<eventNotSelectedListView.size();i++)
        {
        	masterEventNotSelectedListView.add(eventNotSelectedListView.get(i));
        	if(SibIntentService.DEBUG) Log.i(LOG_TAG,eventNotSelectedListView.get(i));
        	t=eventNotSelectedListView.get(i).split("#");
        	eventNotSelectedListView.set(i, t[1]);
        }
        
        
        
        if(SibIntentService.DEBUG) Log.i(LOG_TAG,"onCreate...............................");
        
        
        for(String s : gestureList)
        {
    		HashMap<String, String> singleMapping=new HashMap<String, String>();//creiamo una mappa di valori
	
    		if(SibIntentService.DEBUG) Log.i(LOG_TAG, "Gesture : "+s+" not in preferences");
        	singleMapping.put(GESTURE, s); // per la chiave name,l'informazine sul nome
        	singleMapping.put(DEVICE_EVENT, NULL_ELEMENT);// per la chiave surnaname, l'informazione sul cognome
        	completeMapping.add(singleMapping);
        }
        
        if(superintent.hasExtra("PREVIOUSMAPPING"))
        {
        	if(SibIntentService.DEBUG) Log.i(LOG_TAG, "-------------- Intent not empty!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!" );
        	if (!superintent.getStringExtra("PREVIOUSMAPPING").equals(""))
        	{
	        	String []map=superintent.getStringExtra("PREVIOUSMAPPING").split(";");
	        	for(String s:map)
	        	{
	        		HashMap<String, String> singleMapping=new HashMap<String, String>();
	        		
	        		String []temp=s.split("=");
	        		for(int i=0; i<completeMapping.size();i++)
	        		{
	        			if(completeMapping.get(i).containsValue(temp[0].split("#")[1]))
	        			{
	        				singleMapping.put(GESTURE, temp[0].split("#")[1]); 
				        	singleMapping.put(DEVICE_EVENT, temp[1].split("#")[1]);
				        	eventNotSelectedListView.remove(temp[1].split("#")[1]);
	        				completeMapping.set(i,singleMapping);
	        			}
			        	if(SibIntentService.DEBUG) Log.i(LOG_TAG, "Gesture: "+temp[0].split("#")[1]+" event: "+temp[1].split("#")[1]);
	        		}
	        	}
        	}
        }
        
        
        eventNotSelectedListView.add(NULL_ELEMENT);
			 
		for(HashMap<String,String> m:completeMapping)
	   	{
	   		if(SibIntentService.DEBUG) Log.i(LOG_TAG,m.get(GESTURE));
	   		if(SibIntentService.DEBUG) Log.i(LOG_TAG,m.get(DEVICE_EVENT));
	   	}
		 
        
        listView=(ListView) findViewById(R.id.list);
        
        
        /*
         * --------------------------------------------------------------------impostazioni ricezione risposta dal service
         */
        filter = new IntentFilter(ResponseReceiverMapping.ACTION_RESP_MAPPING);
        filter.addAction(ResponseReceiverMapping.ACTION_LEAVEFROMSIB);
    	filter.addCategory(Intent.CATEGORY_DEFAULT);
    	receiver = new ResponseReceiverMapping();
        
    }
    
    public void onResume()
	 {
		 super.onResume();
		 String[] from={GESTURE,DEVICE_EVENT}; //dai valori contenuti in queste chiavi
		 int[] to={R.id.gesture,R.id.deviceEvent};//agli id dei layout
		 
		 //costruzione dell adapter
		 SimpleAdapter adapter=new SimpleAdapter( MappingActivity.this,
	        		completeMapping,//sorgente dati
	        		R.layout.single_item, //layout contenente gli id di "to"
	        		from,
	        		to);
		 
		OnItemClickListener listener = new OnItemClickListener() {
		
			public void onItemClick(AdapterView<?> parent, View view, int position,long id) 
			{
				
				HashMap<String, String> m=(HashMap<String, String>) parent.getItemAtPosition(position);
				String selection=m.get(GESTURE);
				if(!m.get(DEVICE_EVENT).equals(NULL_ELEMENT))
				{
					/*
					 * ---------------------------------------------------------------------------------------------chiedere conferma?????
					 */
					eventNotSelectedListView.add(m.get(DEVICE_EVENT));
				}
//				Toast.makeText(getApplicationContext(), selection ,Toast.LENGTH_SHORT).show();
				if(eventNotSelectedListView.size()>1)
				{
					Intent intent=new Intent(MappingActivity.this, SelectionEvent.class);
					intent.putExtra("SMARTOBJECT_GESTURE", selection);
					intent.putExtra("SMARTOBJECT_EVENTLISTNOTSELECTED", eventNotSelectedListView);
					startActivityForResult(intent, CHOOSE_MAPPING);
				}
				else
				{
					/*
					 * ----------------------------------------------------------------------------------------------cosa faccio in caso di eventi terminati?
					 */
					Toast.makeText(MappingActivity.this, "No more event!!!!!!!!!", Toast.LENGTH_LONG);
				}
			}
		};
		listView.setOnItemClickListener(listener);
		listView.setAdapter(adapter);
		adapter.notifyDataSetChanged();
		registerReceiver(receiver, filter);
	 }
    
    @Override
    public void onPause()
    {
    	super.onPause();
    	unregisterReceiver(receiver);
    }
    
    public void confirmButton(View v)
	{
    	/*
    	 * implementare conferma e da conferma a intentService che inserisce i dati del mapping in sib
    	 * dalla risposta positiva o negativa a questa activity carico GestureActivity oppure se negativa
    	 * posso rimanere qui, riprovare, o cancellare tutto.
    	 */
    	showDialog(DIALOG_CONFERM_MAPPING);
	}
    
    
    
    protected void onActivityResult(int requestCode,int resultCode, Intent data)
    {
    	String gesture="";
    	String event="";
    	
    	if(requestCode==CHOOSE_MAPPING)
    	{
    		if(resultCode== Activity.RESULT_OK)
    		{
    			Toast.makeText(MappingActivity.this, "OK", Toast.LENGTH_LONG);
    			eventNotSelectedListView=data.getStringArrayListExtra("SMARTOBJECT_EVENTLISTNOTSELECTED");
    			gesture=data.getStringExtra("SMARTOBJECT_GESTURE");
    			event=data.getStringExtra("DEVICE_EVENT");
    			for(HashMap<String, String> m:completeMapping)
    			{
    				if (m.get(GESTURE).equals(gesture))
    				{
    					m.put(DEVICE_EVENT, event);
    				}
    			}
    		}
    		if(resultCode== Activity.RESULT_CANCELED)
    		{
    			Toast.makeText(MappingActivity.this, "Error!!!", Toast.LENGTH_LONG);
    		}
    	}
    }
    
    
    protected Dialog onCreateDialog(int id) {
        Dialog dialog;
        switch(id) {
        case DIALOG_CONFERM_MAPPING:
        	textDialog=new TextView(this);
        	AlertDialog.Builder builder = new AlertDialog.Builder(this);
        	builder.setTitle("Confirm mapping?");
        	textDialog.setText("");
        	builder.setView(textDialog);
        	builder.setIcon(R.drawable.ic_launcher);
        	builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
        		public void onClick(DialogInterface dialog, int id) 
        				{

        		    	connecting=ProgressDialog.show(MappingActivity.this, "Connect", "Connecting....",true, true, new DialogInterface.OnCancelListener() {

						
							public void onCancel(DialogInterface dialog) {
								toast("Interrupted");

							}

						});
        		    	
        		    	Intent intent=new Intent(MappingActivity.this, SibIntentService.class);
        				intent.putExtra(SibIntentService.PARAM_IN_TYPE,SibIntentService.typeIntent.MAPPING);        				
        				
        				/*
        				 * salvo il mapping nelle sharedpreferences
        				 */
        				if(SibIntentService.DEBUG) Log.i(LOG_TAG,"INSERIMENTO MAPPING IN SHAREDPREFERENCES");
        				SharedPreferences pref= getSharedPreferences("PREFERENCES_SMARTOBJECT", Context.MODE_PRIVATE);
        				SharedPreferences.Editor editor= pref.edit();
        				
        				StringBuilder sb = new StringBuilder();
        				for (HashMap<String, String> m:completeMapping) 
        				{
        					if(SibIntentService.DEBUG) Log.i(LOG_TAG,"qui ci sono");
        					String g="";
        					String e="";
//        					for(String s:masterGestureList)
//        					{
//        						if(SibIntentService.DEBUG) Log.i(LOG_TAG,s);
//        					}
        					for(String s:masterGestureList)
        					{
        						String temp=s;
        						String []vtemp=new String[2];
        						vtemp=temp.split("#");
        						if(SibIntentService.DEBUG) Log.i(LOG_TAG,vtemp[1]);
        						if (vtemp[1].equals(m.get(GESTURE)))
        						{
        							g=s;
        						}
        					}
        					for(String s:masterEventNotSelectedListView)
        					{
        						String temp=s;
        						String []vtemp=new String[2];
        						vtemp=temp.split("#");
        						if(SibIntentService.DEBUG) Log.i(LOG_TAG,vtemp[1]);
        						if (vtemp[1].equals(m.get(DEVICE_EVENT)))
        						{
        							e=s;
        						}
        						else if(m.get(DEVICE_EVENT).equals(NULL_ELEMENT))
        						{
        							e=NULL_ELEMENT;
        						}
        					}
        				    sb.append(g).append("=").append(e).append(";");
        				}
        				if(SibIntentService.DEBUG) Log.i(LOG_TAG,sb.toString());
        				editor.putString("COMPLETEMAPPING", sb.toString());
        				editor.commit();
        				
        		    	startService(intent);
        				}
        		});
        	builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
        	public void onClick(DialogInterface dialog, int id) {
        	            dialog.dismiss(); // Chiudiamo la finestra di dialogo
        	            }
        	});
        	dialog = builder.create();
            break;
            
        case DIALOG_INFO_ID:
        	dialog= createInfoDialog();
        	return dialog;
        default:
            dialog = null;
        }
        return dialog;
    }
    
    private Dialog createInfoDialog() {
    	// Otteniamo il riferimento al Builder
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		// Impostiamo il titolo, il messaggio ed una icona in chaining
		builder.setTitle(R.string.alertDialogInfo_label);
		builder.setIcon(R.drawable.ic_launcher);
		builder.setCancelable(false);
		builder.setMessage(R.string.alertDialogInfo_message);
		// Impostiamo il pulsante di Yes con il relativo listener
		builder.setPositiveButton(R.string.alertDialogInfo_positiveLabel,
				new DialogInterface.OnClickListener() {
		
					public void onClick(DialogInterface dialog, int id) {
						dialog.dismiss();
					}
		
				});
		// Ritorniamo l'Alert creato
		return builder.create();
	}
    
    protected void onPrepareDialog(int id,Dialog dialog){
        switch(id){
        case DIALOG_CONFERM_MAPPING:
        	textDialog.setText("");
        	for(HashMap<String, String> m:completeMapping)
        	{
        		textDialog.append(""+m.get(GESTURE)+" ----> "+m.get(DEVICE_EVENT)+"\n");
        	}			
        	break;
        case DIALOG_INFO_ID:
        	break;
        default:
        	break;
        }
    }

    @Override
	public boolean onCreateOptionsMenu(Menu menu) {
    	super.onCreateOptionsMenu(menu);
		menu.add(Menu.FIRST, ITEM_MENU_LEAVE, 1, "Leave");
		menu.add(Menu.FIRST,ITEM_MENU_INFO,2,"Info");
		
		return true;
	}
    
    public boolean onOptionsItemSelected (MenuItem item){

    	switch (item.getItemId())
    	{

    	case ITEM_MENU_LEAVE:
    		myLeave();
    		return true;
    		
    	case ITEM_MENU_INFO :
    		showDialog(DIALOG_INFO_ID);
    		return true;
    		
    	default:
            return true;
    	}
	}
    
    private void myLeave()
    {
    	Intent i = new Intent(this, SibIntentService.class);
    	i.putExtra(SibIntentService.PARAM_IN_TYPE,SibIntentService.typeIntent.LEAVE);
    	startService(i);
    	connecting=ProgressDialog.show(MappingActivity.this, "Leave", "Leaving....",true, true, new DialogInterface.OnCancelListener() {

		
			public void onCancel(DialogInterface dialog) {
				toast("Interrupted");

			}

		});
    }

    @Override
	public void onBackPressed() {
	   myLeave();
	}
    
    private void toast(String text) {
	    Toast.makeText(this, text, Toast.LENGTH_LONG).show();
	}
    
    public class ResponseReceiverMapping extends BroadcastReceiver 
	{
		
	    public static final String ACTION_RESP_MAPPING = "MESSAGE_PROCESSED";
	    public static final String ACTION_LEAVEFROMSIB = SibIntentService.ACTION_LEAVEFROMSIB;
	    
	    @Override
	    public void onReceive(Context context, Intent intent) 
	    {
	    	
	    	if(intent.getAction().equals(ACTION_RESP_MAPPING))
	    	{
	    		if(SibIntentService.DEBUG) Log.i(LOG_TAG," ACTION_RESP_MAPPING :");
		    	boolean r = intent.getBooleanExtra(SibIntentService.PARAM_OUT_RESULT,false);
		    	if(r)
		    	{
		    		connecting.dismiss();
	
		    		Intent i=new Intent(MappingActivity.this, GestureActivity.class);
		    		startActivity(i);
		    		finish();
		    	}
		    	else
		    	{
		    		connecting.dismiss();
		    		toast("Failed connection!");
		    	}
	    	}
	    	else if(intent.getAction().equals(ACTION_LEAVEFROMSIB))
	    	{
	    		if(SibIntentService.DEBUG) Log.i(LOG_TAG," ACTION_LEAVEFROMSIB :");
	    		boolean r = intent.getBooleanExtra(SibIntentService.PARAM_OUT_RESULT,false);
	    		if(r)
	    		{
	    			connecting.dismiss();
	    			finish();
			   	}
			    else
			    {
			    	connecting.dismiss();
			    	toast("Error in leave to SIB");
			    }
	    	}
	    	
    	}
    
	}
    
    
    
}
